#!/usr/bin/python
#-*- coding: utf-8 -*-
#zabbix钉钉报警

import requests, json, sys, os, datetime
# 说明：这里改为自己创建的机器人的webhook的值
webhook = "https://oapi.dingtalk.com/robot/send?access_token=eca6aa375741e88bdaca5d98bdf6185c223570c609da63da60ec348b0e5b3bcf"

user = "zabbix"
# 发给钉钉群中哪个用户
text = sys.argv[1]
# 发送的报警内容
data = {
    "msgtype": "text",
    "text": {
        "content": text
    },
    "at": {
        "atMobiles": [
            user
        ],
        "isAtAll": False
    }
}
print(data)
# 钉钉API固定数据格式
headers = {'Content-Type': 'application/json'}
x = requests.post(url=webhook, data=json.dumps(data), headers=headers)

# 将发送的告警信息写入本地日志/var/log/zabbix/dingding.log中
if os.path.exists("/var/log/zabbix/dingding.log"):
    f = open("/var/log/zabbix/dingding.log", "a+")
else:
    f = open("/var/log/zabbix/dingding.log", "w+")
f.write("\n" + "--" * 30)
if x.json()["errcode"] == 0:
    f.write("\n" + str(datetime.datetime.now()) + "    " + str(user) + "    " + "发送成功" + "\n" + str(text))
    f.close()
else:
    f.write("\n" + str(datetime.datetime.now()) + "    " + str(user) + "    " + "发送失败" + "\n" + str(text))
    f.close()
